package com.cong.project.ws;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cong.project.model.request.TokenUserRequest;
import com.cong.project.utils.JwtUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * @author lhc
 * @date 2022-08-18 09:47
 */
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        List<String> token = request.getHeaders().get("token");
        DecodedJWT decodedJWT = JwtUtils.getTokenInfo(token.get(0));
        Map<String, Claim> claims = decodedJWT.getClaims();
        String userId = claims.get("id").asString();
        String userName = claims.get("nickName").asString();
        int index = userId.lastIndexOf(".");
        //将httpsession对象存储到配置对象中
        sec.getUserProperties().put("userId",Long.valueOf(userId.substring(0, index)));
        sec.getUserProperties().put("userName",userName);
    }
}
